//
//  XS_KCBaseVC.swift
//  XueDao
//
//  Created by 韩云智 on 2020/12/28.
//

import UIKit
import RxCocoa
import RxSwift

class XS_KCBaseVC: XS_BaseVC {
    enum ActionType {
        case 助教
        case 想学
        case 下载
        case 按钮
        case 分享
    }
    
    lazy var btnText = ""
    lazy var id = ""
    var model: XS_KeChengM?
    lazy var dataPS = PublishSubject<XS_KeChengM>()
    lazy var ss = getScroll()
    lazy var btnTypePS = PublishSubject<(String, UIColor)>()
    func onAction(_ type: ActionType) {
        guard let model = model else { return }
        switch type {
        case .助教:
//            let assistantsVC = XS_MineAssistantsVC()
//            XS_NVC.shared.pushViewController(assistantsVC, animated: true)
            let qidianUrl = "https://wpa1.qq.com/gPNerizz?_type=wpa&qidian=true"
            let webVC = XS_WebPageVC()
            webVC.loadUrl(qidianUrl)
            XS_NVC.shared.pushViewController(webVC, animated: true)
        case .分享:
//            guard let url = URL(string: "/course?id=\(model.curriculum.id)".spliceH5Api()) else { return }
//            let activityVc = UIActivityViewController(activityItems: [url], applicationActivities: nil)
//            XS_NVC.shared.present(activityVc, animated: true)
            let inviteVC = XS_InviteVC()
            XS_NVC.shared.pushViewController(inviteVC, animated: true)
        case .想学:
            if model.curriculum.isCollect == "yes" {
                model.curriculum.isCollect = "no"
                _ = XS_NetWork.requestJson("/collection/collectionCancel", parameters: ["relation":model.curriculum.id,"type":"curriculum"])
                    .subscribe()
            } else {
                model.curriculum.isCollect = "yes"
                _ = XS_NetWork.requestJson("/collection/collectionButton", parameters: ["relation":model.curriculum.id,"type":"curriculum"])
                    .subscribe()
            }
            dataPS.onNext(model)
        case .按钮:
            switch btnText {
            case "立即学习":
                guard XS_Singleton.shared.infoModel != nil else {
                    XS_NVC.shared.toLogin(false)
                    return
                }
                goToStudyNow(model: model)
            case "立即领取":
                guard XS_Singleton.shared.infoModel != nil else {
                    XS_NVC.shared.toLogin(false)
                    return
                }
                
//                let buyVC = XS_BuyVC()
//                buyVC.courseId = self.id
//                buyVC.courseClassification = "online"
//                navigationController?.pushViewController(buyVC, animated: true)
                XS_NetWork.requestJson("/order/payMoneyByOrder", parameters: ["courseId":model.curriculum.id, "courseClassification":"online"])
                    .subscribe(onNext: { [weak self] resp in
                        guard let `self` = self, resp.success else { return }
                        self.reloadModel()
                        self.goToStudyNow(model: model)
                    }).disposed(by: disposeBag)
            case "立即购买":
                guard XS_Singleton.shared.infoModel != nil else {
                    XS_NVC.shared.toLogin(false)
                    return
                }
                let buyVC = XS_BuyVC()
                buyVC.courseId = self.id
                buyVC.courseClassification = "online"
                navigationController?.pushViewController(buyVC, animated: true)
            default: break
            }
        case .下载:
            let startVC = XS_DownloadStartVC()
            startVC.id = id
            startVC.curriculumModel = model.curriculum
            startVC.title = "选择下载"
            navigationController?.pushViewController(startVC, animated: true)
            break
        default: break
        }
    }
    
    func goToStudyNow(model: XS_KeChengM) {
        XS_NetWork.requestJson("/hour/queryHours", parameters: ["id":model.curriculum.id])
            .mapModels(type: XS_KCqueryHoursM.self)
            .subscribe(onNext: { [weak self] models, resp in
                guard let `self` = self, let item = models.first?.curriculumHourDtoList.first else {
                    let alertVC = UIAlertController.init(title: "", message: "系统错误，请在我的板块中进行反馈", preferredStyle: .alert)
                    let alertAction = UIAlertAction.init(title: "确定", style: .cancel) { (action) in
                    }
                    alertVC.addAction(alertAction)
                    XS_NVC.shared.viewControllers.first?.navigationController?.present(alertVC, animated: true, completion: nil)
                    return
                }
                XS_NetWork.requestJson("/file/playVideo", parameters: ["id":item.id])
                    .mapModel(type: XS_KCplayVideoM.self)
                    .subscribe(onNext: { [weak self] video, resp in
                        guard let `self` = self else { return }
                        if resp.code == "00403" { // 购买
                            guard XS_Singleton.shared.infoModel != nil else {
                                XS_NVC.shared.toLogin(false)
                                return
                            }
                            let buyVC = XS_BuyVC()
                            buyVC.courseId = "\(model.curriculum.id)"
                            buyVC.courseClassification = "online"
                            XS_NVC.shared.pushViewController(buyVC, animated: true)
                            return
                        }
                        guard resp.success, let video = video else { return }
                        let vc = XS_KCDetailVC()
                        vc.curriculum = model.curriculum
                        vc.model = video
                        vc.id = item.id
                        self.navigationController?.pushViewController(vc, animated: true)
                    }).disposed(by: self.disposeBag)
            }).disposed(by: disposeBag)
    }
    
    func upScroll(_ top: UIView) {}
    
    override func upConfig() {
        shouldNavBarHidden = true
        isStatusBarBlack = false
    }
    override func upView() {
        view.addSubview(ss)
        let bottom = getBottomView()
        view.addSubview(bottom)
        let top = UIView()
        top.alpha = 0
        top.backgroundColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
        view.addSubview(top)
        loadCustomBar()
        
        top.snp.makeConstraints({
            $0.left.right.top.equalToSuperview()
            $0.bottom.equalTo(customBar.snp.bottom)
        })
        bottom.snp.makeConstraints({
            $0.left.right.bottom.equalToSuperview()
            $0.height.equalTo(.scale*50 + .bottomHeight)
        })
        ss.snp.makeConstraints({
            $0.left.right.top.equalToSuperview()
            $0.bottom.equalTo(bottom.snp.top)
        })
        
        ss.rx.contentOffset
            .subscribe(onNext: { offset in
                top.alpha = offset.y / (.scale*240 - 44 - .barHeight)
            }).disposed(by: disposeBag)
        
        
        let share = QMUIButton()
        share.setBackgroundImage(UIImage(named: "icon_分享备份"), for: .normal)
        view.addSubview(share)
        share.snp.makeConstraints({
            $0.width.height.equalTo(24)
            $0.centerY.equalTo(customBar.snp.centerY)
            $0.right.equalTo(-16)
        })
        share.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                self?.onAction(.分享)
            }).disposed(by: disposeBag)
        
        
//        let xiangxue = QMUIButton()
//        xiangxue.isHidden = true
//        xiangxue.setBackgroundImage(UIImage(named: "icon_24px_收藏_1"), for: .normal)
//        xiangxue.setBackgroundImage(UIImage(named: "icon_64_收藏_绿_1"), for: .selected)
//        view.addSubview(xiangxue)
//        xiangxue.snp.makeConstraints({
//            $0.width.height.equalTo(24)
//            $0.centerY.equalTo(customBar.snp.centerY)
//            $0.right.equalTo(-56)
//        })
//        xiangxue.rx.tap.asDriver()
//            .drive(onNext: { [weak self] in
//                self?.onAction(.想学)
//            }).disposed(by: disposeBag)
        
        
        let img = UIImage(named: "icon_下载")
        let dl = UIView()
        dl.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        dl.frame = CGRect(origin: .zero, size: img?.size ?? .zero)
        let imgV = UIImageView(image: img)
        imgV.frame = dl.bounds
        dl.mask = imgV
        let download = QMUIButton()
        download.isHidden = true
        download.setBackgroundImage(dl.xsToImage(), for: .normal)
        view.addSubview(download)
        download.snp.makeConstraints({
            $0.width.height.equalTo(24)
            $0.centerY.equalTo(customBar.snp.centerY)
            $0.right.equalTo(-56)
        })
        download.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                self?.onAction(.下载)
            }).disposed(by: disposeBag)
        
        
        let topImgV = UIImageView()
        topImgV.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        ss.addSubview(topImgV)
        topImgV.snp.makeConstraints({
            $0.top.left.width.equalToSuperview()
            $0.height.equalTo(.scale*240)
        })
        let titleView = XS_KCTitle()
        ss.addSubview(titleView)
        titleView.snp.makeConstraints({
            $0.left.width.equalToSuperview()
            $0.top.equalTo(topImgV.snp.bottom)
        })
        let priceView = XS_KCPrice()
        ss.addSubview(priceView)
        priceView.snp.makeConstraints({
            $0.left.width.equalToSuperview()
            $0.top.equalTo(titleView.snp.bottom)
            $0.height.equalTo(.scale * 50)
        })
        
        dataPS.subscribe(onNext: { model in
            let isBuy = model.curriculum.isBuy == "yes" // 当前用户是否购买该课程(购买yes 未购买no 游客no)
            let isCollect = model.curriculum.isCollect == "yes"  // 当前用户是否收藏该课程(收藏yes 未收藏no)
            let isOnline = model.curriculum.curriculumForm == "online" // 是否线上课
            let isFree = model.curriculum.isFree == "userFree" // 是否免费（是：userFree，否：userPay）
            let isVip = XS_Singleton.shared.infoModel?.userBO.userTypeEnum() == XS_UserType.vip
            download.isHidden = !isBuy
//            xiangxue.isHidden = isBuy
//            xiangxue.isSelected = isCollect
            topImgV.sd_setImage(with: URL(string: model.curriculum.curriculumImgUrl))
            titleView.modelPS.onNext((model.curriculum.curriculumName, model.curriculum.label.components(separatedBy: ",")))
            if isBuy {
                priceView.modelPS.onNext((nil, nil, nil))
                priceView.snp.updateConstraints { (make) in
                    make.height.equalTo(1)
                }
            } else {
                let item = model.curriculum!
//                let (p, dp) = xsGetPrice(vipIsFree: item.vipIsFree, isFree: item.isFree, vipPrice: item.vipPrice, discountPrice: item.discountPrice, price: item.price)
//                priceView.modelPS.onNext((model.curriculum.purchaseNum, p, dp))
                
                let purchaseNumStr = isFree ? "已有\(item.purchaseNum)人领取" : (isOnline ? "已有\(item.purchaseNum)人购买" : "已有\(item.purchaseNum)人报名")
                if isOnline == false {
                    if isFree {
                        priceView.modelPS.onNext((purchaseNumStr, "0", nil)) // 免费
                    } else {
                        priceView.modelPS.onNext((purchaseNumStr, item.price, nil)) // 原价
                    }
                } else {
                    if isFree {
                        priceView.modelPS.onNext((purchaseNumStr, "0", nil)) // 优惠价、会员价
                    } else {
                        if isVip {
                            if model.curriculum.vipIsFree == "vipFree" { // 会员免费
                                priceView.modelPS.onNext((purchaseNumStr, "0", item.price)) // 会员价、原价
                            } else {
                                priceView.modelPS.onNext((purchaseNumStr, item.vipPrice, item.price)) // 会员价、原价
                            }
                        } else {
                            if model.curriculum.vipIsFree == "vipFree" { // 会员免费
                                priceView.modelPS.onNext((purchaseNumStr, item.discountPrice, "0")) // 优惠价、会员价
                            } else {
                                priceView.modelPS.onNext((purchaseNumStr, item.discountPrice, item.vipPrice)) // 优惠价、会员价
                            }
                        }
                    }
                }
//                if isFree {
//                    priceView.modelPS.onNext((model.curriculum.purchaseNum, "0", model.curriculum.price))
//                } else if model.curriculum.discountPrice.count > 0 {
//                    priceView.modelPS.onNext((model.curriculum.purchaseNum, model.curriculum.discountPrice, model.curriculum.price))
//                } else {
//                    priceView.modelPS.onNext((model.curriculum.purchaseNum, model.curriculum.price, nil))
//                }
            }
        }).disposed(by: disposeBag)
        
        XS_NetWork.requestJson("/curriculum/queryCurriculumById", parameters: ["id":id])
            .mapModel(type: XS_KeChengM.self)
            .subscribe(onNext: { [weak self] model, resp in
                guard let `self` = self, resp.success, let model = model else { return }
                self.model = model
                self.upScroll(priceView)
                self.dataPS.onNext(model)
            }).disposed(by: disposeBag)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        guard model != nil else { return }
        reloadModel()
    }
    func reloadModel() {
        XS_NetWork.requestJson("/curriculum/queryCurriculumById", parameters: ["id":id])
            .mapModel(type: XS_KeChengM.self)
            .subscribe(onNext: { [weak self] model, resp in
                guard let `self` = self, resp.success, let model = model else { return }
                self.model = model
                self.dataPS.onNext(model)
            }).disposed(by: disposeBag)
    }
    
    
    private func getScroll() -> UIScrollView {
        let scroll = UIScrollView()
        scroll.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        scroll.bounces = false
        scroll.contentInsetAdjustmentBehavior = .never
        scroll.showsVerticalScrollIndicator = false
        return scroll
    }
    private func getBottomView() -> UIView {
        let view = UIView()
        view.isHidden = true
        view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        
        let zhujiao = QMUIButton()
        zhujiao.imagePosition = .top
        zhujiao.setImage(UIImage(named: "icon_24px_客服"), for: .normal)
        zhujiao.setTitle("助教", for: .normal)
        zhujiao.setTitleColor(#colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1), for: .normal)
        zhujiao.titleLabel?.font = .xsFont(.scale*12)
        view.addSubview(zhujiao)
        zhujiao.snp.makeConstraints({
            $0.width.equalTo(.scale*28)
            $0.height.equalTo(.scale*40)
            $0.top.equalTo(.scale*6)
            $0.left.equalTo(.scale*14)
        })
        
        
        let xiangxue = QMUIButton()
        xiangxue.isHidden = true
        xiangxue.imagePosition = .top
        xiangxue.setImage(UIImage(named: "icon_24px_收藏"), for: .normal)
        xiangxue.setImage(UIImage(named: "icon_24px_收藏备份"), for: .selected)
        xiangxue.setTitle("收藏", for: .normal)
        xiangxue.setTitleColor(#colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1), for: .normal)
        xiangxue.titleLabel?.font = .xsFont(.scale*12)
        view.addSubview(xiangxue)
        xiangxue.snp.makeConstraints({
            $0.width.equalTo(.scale*28)
            $0.height.equalTo(.scale*40)
            $0.top.equalTo(.scale*6)
            $0.left.equalTo(.scale*59)
        })
        
        
        let download = QMUIButton()
        download.isHidden = true
        download.imagePosition = .top
        download.setImage(UIImage(named: "icon_24px_收藏"), for: .normal)
        download.setImage(UIImage(named: "icon_24px_收藏备份"), for: .selected)
//        download.setImage(UIImage(named: "icon_下载"), for: .normal)
        download.setTitle("收藏", for: .normal)
        download.setTitleColor(#colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1), for: .normal)
        download.titleLabel?.font = .xsFont(.scale*12)
        view.addSubview(download)
        download.snp.makeConstraints({
            $0.width.equalTo(.scale*28)
            $0.height.equalTo(.scale*40)
            $0.top.equalTo(.scale*6)
            $0.left.equalTo(.scale*59)
        })
        
        
        let btn = QMUIButton()
        btn.layer.cornerRadius = .scale*20
        btn.setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal)
        btn.titleLabel?.font = .xsFont(name: .medium, .scale*16)
        view.addSubview(btn)
        btn.snp.makeConstraints({
            $0.width.equalTo(.scale*253)
            $0.height.equalTo(.scale*40)
            $0.top.equalTo(.scale*5)
            $0.right.equalTo(-.scale*16)
        })
        
        download.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                self?.onAction(.想学)
            }).disposed(by: disposeBag)
        xiangxue.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                self?.onAction(.想学)
            }).disposed(by: disposeBag)
        zhujiao.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                self?.onAction(.助教)
            }).disposed(by: disposeBag)
        btn.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                self?.onAction(.按钮)
            }).disposed(by: disposeBag)
        
        dataPS.subscribe(onNext: { model in
            let isBuy = model.curriculum.isBuy == "yes" // 当前用户是否购买该课程(购买yes 未购买no 游客no)
            let isCollect = model.curriculum.isCollect == "yes"  // 当前用户是否收藏该课程(收藏yes 未收藏no)
            download.isHidden = !isBuy
            download.isSelected = isCollect
            xiangxue.isHidden = isBuy
            xiangxue.isSelected = isCollect
        }).disposed(by: disposeBag)
        btnTypePS.subscribe(onNext: { [weak self] text, color in
            self?.btnText = text
            btn.setTitle(text, for: .normal)
            btn.layer.backgroundColor = color.cgColor
            view.isHidden = false
        }).disposed(by: disposeBag)
        return view
    }
}
